#include <iostream>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <cstring>
#include <cerrno>
#include <string>


std::string getOtherMsg()
{
    static int cnt = 0; // 用于计数，是第几次写入

    std::string msgid = std::to_string(cnt++); // 第几次写入，转换为字符串
    std::string self_id = std::to_string(getpid()); // 进程id，转换为字符串

    // 将各个信息组合
    std::string msg = "messageid is ";
    msg += msgid;
    msg += ", my pid is ";
    msg += self_id;

    return msg;
}

void SubProcessWrite(int wfd)
{
    std::string msg = "I am child process!";

    // 一直写入
    int pipesize = 0;
    char ch = 'A';
    while(1)
    {
        std::string info = msg + getOtherMsg();
        // 将数据写入管道
        write(wfd, info.c_str(), info.size()); // 向文件中写入时，不必写入\0

        // write(wfd, &ch, 1);
        // std::cout << "pipesize: " << ++pipesize << ", write char: " << ch++ << std::endl;
        // if (ch == 'G') break;
    }
}

void FatherProcessRead(int rfd)
{
    char inbuffer[1024];
    // 一直读取
    while(1)
    {
        std::cout << std::endl;
        ssize_t n = read(rfd, inbuffer, sizeof(inbuffer)-1);

        if (n > 0)
        {
            // 读取成功，读入 n 个字符
            inbuffer[n] = 0; // 设置 \0
            std::cout << "father get msg: " << inbuffer << std::endl;
        }
        else if (n == 0)
        {
            // 写端关闭，读到文件末尾
            std::cout << "client quit, father get return val: " << n << ", father quit, too!" << std::endl;
            break;
        }
        sleep(2);
    }
}
int main()
{
    // 1.创建匿名管道
    int pipefd[2];
    int n = pipe(pipefd);
    if (n != 0)
    {
        // 创建管道失败
        std::cerr << "errno: " << errno << ",errstring: " << strerror(errno) << std::endl;
        return 1;
    }

    // 打印fd
    std::cout << "读端：" << pipefd[0] << "写端：" << pipefd[1] << std::endl;
    sleep(1);

    // 2.创建子进程
    pid_t pid = fork();
    if (pid == 0)
    {
        std::cout << "子进程关闭不需要的文件，准备开始写入了" << std::endl;
        sleep(1);

        // 3.子进程关闭读文件
        close(pipefd[0]);
        SubProcessWrite(pipefd[1]);

        // 结束
        close(pipefd[1]);
        exit(0);
    }

    std::cout << "父进程关闭不需要的文件，准备开始读取了" << std::endl;
    sleep(1);

    // 3.父进程关闭写文件
    close(pipefd[1]);
    FatherProcessRead(pipefd[0]);

    std::cout << "father will quit in 5s!" << std::endl;
    sleep(5);
    // 结束
    close(pipefd[0]);

    // 等待子进程
    int status = 0;
    pid_t ret = waitpid(pid, &status, 0);
    if (ret > 0)
    {
        std::cout << "wait child sucess, exit_sig: " << (status & 0x7f) << std::endl;
        std::cout << "wait child sucess, exit_code: " << ((status >> 8)&0xff) << std::endl;
    }
    return 0;
}